package com.ershui.blog.system.util;

import com.alibaba.fastjson.annotation.JSONField;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class MapUtil {
    /**
     * object to map
     *
     * @param object
     * @return
     */
    public static Map<String, Object> toMap(Object object) {
        Map<String, Object> map = new HashMap<>(16);
        if (object == null) {
            return map;
        }

        try {
            Field[] fields = object.getClass().getDeclaredFields();
            for (Field field : fields) {
                if (field == null || field.getName() == null) {
                    continue;
                }
                field.setAccessible(true);
                String key = field.getName();
                JSONField jsonField = field.getDeclaredAnnotation(JSONField.class);
                if (jsonField != null) {
                    key = jsonField.name();
                }
                map.put(key, field.get(object));
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * object to map
     *
     * @param object
     * @param ignore
     * @return
     */
    public static Map<String, Object> toMap(Object object, boolean ignore) {
        Map<String, Object> map = new HashMap<>(16);
        if (object == null) {
            return map;
        }

        try {
            Field[] fields = object.getClass().getDeclaredFields();
            for (Field field : fields) {
                if (field == null || field.getName() == null) {
                    continue;
                }
                field.setAccessible(true);
                if (ignore && field.get(object) == null) {
                    continue;
                }
                String key = field.getName();
                JSONField jsonField = field.getDeclaredAnnotation(JSONField.class);
                if (jsonField != null) {
                    key = jsonField.name();
                }
                map.put(key, field.get(object));
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return map;
    }
}
